/**
 * Created by ruiyuan on 15-9-4.
 */
var Question = mongoose.model('question');
var toolUtil = require('../common/utils/toolUtil');
var questionPraise = mongoose.model('question_praise');
var QuestionReplyThank = mongoose.model('question_replythanks');
var replyAt = mongoose.model('question_replyAt');
var replyIndex = mongoose.model('reply_index');
var async = require('async');
var Banner = mongoose.model('banner');
var geolib = require('geolib');
var Users = mongoose.model('user');
var userCommunity = mongoose.model('user_community');

/*  宝宝树66小区二次改造    add   guo.xiaomin  20170807   start   */
var communityService = require('./communityService');
/*  宝宝树66小区二次改造    add   guo.xiaomin  20170807   end   */

exports.getAllList = function (user, ts, range, callback) {

    var key = 'community:' + user.community._id + ':question:list';
    if (range == 'around') {
        key = 'community:around:' + user.community._id + ':question:list';
    }

    var max = '+inf';
    if (ts != '0') {
        max = ts;
    }

    var args = [key, '(' + max, '-inf', 'WITHSCORES', 'LIMIT', 0, listPageSize];

    redisClient.ZREVRANGEBYSCORE(args, function (err, result) {

        if (err) {
            callback(err)
        } else {
            var value = [];
            result.forEach(function (tmp, i) {
                if (i % 2 == 0) {
                    value[i / 2] = {};
                    value[i / 2].id = tmp;
                } else {
                    value[(i - 1) / 2].score = tmp;
                }
            });

            var map = {};
            value.forEach(function (m) {
                map[m.id] = m.score;
            });

            Question.find({
                community: user.community._id,
                isValid: true,
                topBeginDate: {$lte: new Date()},
                topEndDate: {$gte: new Date()}
            }, 'praiseCount _id desc categoryOrder community replies score ' +
                'category status images replies dateCreated createdBy')
                .populate('replies.repliedBy', '_id nickName images userType authenticationStatus')
                .populate('community', '_id communityName')
                .populate('createdBy', '_id nickName images authenticationStatus roomUnit showUnit userRole exp')
                .limit(1)
                .exec(function (err, tops) {
                    var ids = [];
                    var idList = [];
                    if (tops != null || tops.length > 0) {
                        value.forEach(function (redisId) {
                            var flag = true;
                            for (i = 0; i < tops.length; i++) {
                                if (redisId.id == tops[i]._id + '') {
                                    flag = false;
                                    break;
                                }
                            }
                            if (flag) {
                                ids.push(redisId);
                                idList.push(redisId.id);
                            }
                        })
                    }

                    Question.find({_id: {$in: idList}}, 'praiseCount _id desc categoryOrder community replies score ' +
                        'category status images replies dateCreated createdBy')
                        .populate('replies.repliedBy', '_id nickName images userType authenticationStatus')
                        .populate('community', '_id communityName')
                        .populate('createdBy', '_id nickName images authenticationStatus roomUnit showUnit userRole exp')
                        .exec(function (err, results) {
                            async.each(results, function (question, callbackInner) {

                                question._doc.redisScore = map[question._id];

                                //回复数、点赞数
                                question._doc['replyCountStr'] = toolUtil.transformNumber(question.replies.length);
                                question._doc.praiseCount = toolUtil.transformNumber(question.praiseCount);

                                //采纳回复
                                question.replies.forEach(function (reply) {
                                    if (reply.replyStatus == '已采纳') {
                                        question._doc['adoptedReply'] = reply;
                                    }
                                });
                                question.replies = undefined;

                                //用户等级
                                question.createdBy._doc.level = toolUtil.getUserLevel(question.createdBy.exp ? question.createdBy.exp : 0);

                                //单元号
                                var isOtherCommunity = user.community._id != question.community._id + '';
                                if (question.createdBy.roomUnit != null && question.createdBy.roomUnit != '')
                                    question.createdBy._doc.roomUnit = !isNaN(question.createdBy.roomUnit) ? question.createdBy.roomUnit + '单元' : question.createdBy.roomUnit;
                                if ((question.createdBy.showUnit != null && !question.createdBy.showUnit) || isOtherCommunity) {
                                    question.createdBy.roomUnit = undefined;
                                }

                                //分享url
                                question._doc.shareUrl = 'http://' + backOfficeHost + QUESTION_SHARE_URL + '?v=1.0';

                                async.parallel([
                                    function (callbackInner) {              //是否点赞
                                        questionPraise.findOne({
                                            question: question._id, user: user._id
                                        }, function (err, result) {
                                            question._doc.isPraise = result != null;
                                            callbackInner();
                                        })
                                    },
                                    function (callbackInner) {              //采纳回复替换@
                                        if (question._doc.adoptedReply != null && question._doc.adoptedReply.replyDesc.indexOf(atFlag) != -1) {
                                            replyAt.findOne({replyId: question._doc.adoptedReply._id + ''}, function (err, at) {
                                                if (at != null && at.uList != null) {
                                                    at.uList.forEach(function (temp, i) {
                                                        question._doc.adoptedReply.replyDesc = question._doc.adoptedReply.replyDesc.replace(new RegExp("@\\{" + i + "\\}"), '@' + temp.nickName + ' ')
                                                    });
                                                }
                                                callbackInner();
                                            }).populate('uList', '_id nickName');
                                        } else {
                                            callbackInner();
                                        }
                                    }
                                ], function (err) {
                                    callbackInner();
                                })
                            }, function (err) {

                                results.sort(function (a, b) {
                                    return Number(b._doc.redisScore) - Number(a._doc.redisScore);
                                });

                                var res = {
                                    nextTs: ids.length > 0 ? Number(ids[ids.length - 1].score) : 0,
                                    list: results
                                };

                                if (ts == '0') {
                                    exports.questionsHandle(tops, user, function (err, tops) {
                                        res.topList = tops;
                                        callback(err, res)
                                    })
                                } else {
                                    callback(err, res);
                                }
                            })
                        });
                })
        }
    })

};

/**
 * 全部列表
 * @param user
 * @param ts
 * @param range
 * @param sort
 * @param direction
 * @param callback
 */
/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170807   start   */
// 前端选择其他小区-共同方法多加一个参数
exports.getMutualAllListService = function (user, ts, range, sort, direction, callback) {

    if (sort == 'smart') {
        exports.getAllList(user, ts, range, callback)
    } else {
        exports.getListService(user, ts, direction, range, 'all', null, 0, null, null, callback);
    }
};
/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170807   end   */

/**
 * 求助列表
 * @param user
 * @param ts        时间戳
 * @param range     范围
 * @param direction 方向
 * @param status    状态
 * @param callback
 */
/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170807   start   */
// 前端选择其他小区
exports.getQuestionListService = function (user, ts, range, direction, status, currCommunityId, currCityId, callback) {


    // 新：前端传递小区
    redisClient.HGET('community:user:count', currCommunityId, function (err, value) {
        // 旧：原来是取得登陆用户所在小区
        // redisClient.HGET('community:user:count', user.community._id, function (err, value) {
        exports.getListService(user, ts, direction, range, 'question', status, Number(value), currCommunityId, currCityId, function (err, result) {
            if (direction == 'top') {

                Banner.find(
                    {
                        beginDate: {$lte: new Date()},
                        endDate: {$gte: new Date()},
                        type: 1,
                        isValid: true,
                        "$or": [
                            //{community: user.community._id},
                            // {city: user.community.cityId}, // 旧
                            {city: currCityId}, // 新
                            //{province: user.community.provinceId},
                            //{county: user.community.countyId},
                            {level: 0}]
                    }
                    , '_id url imageURL name openType contentId').exec(function (err, temp) {
                        var bannerList = [];
                        if (temp != null) {
                            temp.forEach(function (banner) {
                                var temp = {
                                    category: 'banner',
                                    url: banner.url,
                                    images: [{
                                        imageURL: imgHost + banner.imageURL + '?imageView2/1/h/276/w/750/q/75'
                                    }],
                                    bannerIndex: bannerIndex
                                };
                                if (banner.openType) temp.openType = banner.openType;
                                if (banner.contentId) temp.contentId = banner.contentId;

                                bannerList.push(temp);
                            })
                        }
                        if (bannerList.length > 0) {


                            result.banner = bannerList[0];
                            result.bannerList = bannerList;
                        }

                        callback(err, result);
                    });
            } else {
                callback(err, result);
            }
        })
    });
};
/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170807   end   */

/**
 * 分享列表
 * @param user
 * @param ts        时间戳
 * @param range     范围
 * @param direction
 * @param callback
 */
/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170807   start   */
// 前端选择其他小区
// exports.getShareListService = function (user, ts, range, direction, callback) { // 旧:无前台传递小区
exports.getShareListService = function (user, ts, range, direction, currCommunityId, currCityId, callback) { // 新:前台传递小区

    // 新：前端传递小区
    redisClient.HGET('community:user:count', currCommunityId, function (err, value) {
        // 旧：原来是取得登陆用户所在小区
        // redisClient.HGET('community:user:count', user.community._id, function (err, value) {
        exports.getListService(user, ts, direction, range, 'share', null, Number(value), currCommunityId, currCityId, function (err, result) {
            if (direction == 'top') {

                Banner.find({
                    beginDate: {$lte: new Date()},
                    endDate: {$gte: new Date()},
                    type: 3,
                    isValid: true,
                    $or: [
                        //{community: user.community._id},
                        // {city: user.community.cityId}, // 旧
                        {city: currCityId}, // 新
                        //{province: user.community.provinceId},
                        //{county: user.community.countyId},
                        {level: 0}]
                }, '_id url imageURL name openType contentId').exec(function (err, temp) {
                    var bannerList = [];
                    if (temp != null) {
                        temp.forEach(function (banner) {
                            var temp = {
                                category: 'banner',
                                url: banner.url,
                                images: [{
                                    imageURL: imgHost + banner.imageURL + '?imageView2/1/h/276/w/750/q/75'
                                }],
                                bannerIndex: bannerIndex
                            };
                            if (banner.openType) temp.openType = banner.openType;
                            if (banner.contentId) temp.contentId = banner.contentId;

                            bannerList.push(temp);
                        })
                    }
                    if (bannerList.length > 0) {


                        result.banner = bannerList[0];
                        result.bannerList = bannerList;
                    }

                    callback(err, result);
                });
            } else {
                callback(err, result);
            }

        })
    });
};
/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170807   end   */


/**
 * 闲聊列表
 * @param user
 * @param ts
 * @param range
 * @param direction
 * @param callback
 */
/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170807   start   */
// 前端选择其他小区-共同方法加了一个参数
exports.getTalkListService = function (user, ts, range, direction, callback) {
    exports.getListService(user, ts, direction, range, 'advertisement', null, 0, null, null, callback);
};
/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170807   end   */

exports.getEssenceListService = function (user, ts, range, callback) {

    if (ts == '0') {
        ts = new Date().getTime();
    }

    var opt = {
        isValid: true,
        dateCreated: {$lt: Number(ts)},
        fromFlag: {$ne: 'service'},
        //category: 'question',
        level: 1
        //$or: [{level: 1}, {'replies.9': {$exists: true}}
        //, {
        //    'replies.34': {$exists: true},
        //    category: 'share',
        //    'images.1': {$exists: true}
        //}
        //]
    };

    if (range == 'around') {                //全城
        opt['$or'] = [{fromFlag: 'operate'}, {city: user.community.cityId}]
    } else {                                //本小区
        opt.community = user.community._id;
    }


    Question.find(opt, 'praiseCount _id desc categoryOrder community replies score ' +
        'category status images replies dateCreated createdBy')
        .populate('replies.repliedBy', '_id nickName images userType authenticationStatus')
        .populate('community', '_id communityName location')
        .populate('createdBy', '_id nickName images authenticationStatus roomUnit showUnit userRole exp')
        .sort({dateCreated: -1}).limit(listPageSize).exec(function (err, result) {
            if (err) {
                callback(err, null)
            } else {
                exports.questionsHandle(result, user, function (err, results) {
                    var data = {};

                    if (results.length > 0)
                        data.nextTs = results[results.length - 1].dateCreated.getTime();
                    data.list = results;
                    callback(err, data);
                });
            }
        });
};

var ACTIVE_COMMUNITY = [
    '549968e5bc537bb017132f01',
    '5527c49d23c19c113b71697f',
    '552dddd53cb849936aa01322',
    '552e10126fdc32c16fa394f8',
    '5550855f984690a3257ce639',
    '55519ba1b78c41462b9d7169',
    '5551ada2b78c41462b9dafbe',
    '5559e61a5655bc2445bd603b',
    '555af9d199e117a44899a9c4',
    '55668b2cad17e99b542190e0',
    '5570fbbd319d846b016a0ea8',
    '559e3c5ae03a534067fe29f4',
    '5583bd569bf44ad8765530ae',
    '558a21ea24f62c41422606e7',
    '55508708984690a3257ceb4f',
    '55ff83c5f0b3fa0703e49c35'
];

/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170807   start   */
// 前端选择其他小区
// exports.getListService = function (user, ts, direction, range, category, status, number, callback) { // 旧:无前台传递小区
exports.getListService = function (user, ts, direction, range, category, status, number, currCommunityId, currCityId, callback) { // 新:前台传递小区

    if (currCommunityId != null && currCommunityId == '564310b186acfe4f5fa87b4d') { // 新：前端传递小区
        // if (user.community._id == '564310b186acfe4f5fa87b4d') { // 旧：原来是取得登陆用户所在小区
            range = null;
    }

    var opt = {
        isValid: true
    };

    //if (category != 'all') {
    //    opt.category = category;
    //}

    if (status == 'unsolved') {
        opt.status = '未解决'
    }

    if (direction == 'top') {
        opt.dateCreated = {$gt: new Date(Number(ts))}
    } else if (direction == 'down') {
        // opt.dateCreated = {$lt: new Date(Number(ts))}
        opt.dateCreated = {$lt: Number(ts)}
    }

    if (ts == '0') {
        delete  opt.dateCreated;
    }

    if (range == 'around') {    //周边小区
        if (user.community.communityType == 0) {
            opt.fromFlag = {$ne: 'service'};

            opt['$or'] = [{}];
            if (category == 'question') {
                opt['$or'] = [{category: 'question'}, {category: 'lostAndFound'}];
            } else if (category == 'share') {
                opt['$or'] = [{category: 'share'}, {category: 'advertisement'}];
            }
            //} else if ((user.userRole != null && user.userRole.length > 0 && user.userRole.indexOf(3) != -1)) {
            //    opt.fromFlag = {$ne: 'service'};
            //    opt['$and'] = [{
            //        $or: [{community: user.community._id}, {
            //            city: user.community.cityId,
            //            'aroundCommunity.0': {$exists: true}
            //        }, {fromFlag: 'operate'}]
            //    }];
            //    if (category == 'question') {
            //        opt['$and'].push({$or: [{category: 'question'}, {category: 'lostAndFound'}]})
            //    } else if (category == 'share') {
            //        opt['$and'].push({$or: [{category: 'share'}, {category: 'advertisement'}]})
            //    } else if (category == 'all') {
            //        delete opt['$and'];
            //        opt['$or'] = [{
            //            city: user.community.cityId,
            //            'aroundCommunity.0': {$exists: true}
            //        }, {fromFlag: 'operate'}]
            //    }
            //} else if (number <= 200) {
            //    opt['$and'] = [{
            //        $or: [{community: user.community._id}, {fromFlag: 'operate'}, {
            //            city: user.community.cityId,
            //            fromFlag: {$ne: 'service'},
            //            desc: {$type: 2},
            //            $where: "this.desc.length>12",
            //            'aroundCommunity.0': {$exists: true}
            //        }, {
            //            city: user.community.cityId,
            //            fromFlag: {$ne: 'service'},
            //            'images.0': {$exists: true},
            //            'aroundCommunity.0': {$exists: true}
            //        }]
            //    }];
            //
            //    if (category == 'question') {
            //        opt['$and'].push({$or: [{category: 'question'}, {category: 'lostAndFound'}]})
            //    } else if (category == 'share') {
            //        opt['$and'].push({$or: [{category: 'share'}, {category: 'advertisement'}]})
            //    } else if (category == 'all') {
            //        delete opt['$and'];
            //        opt['$or'] = [{
            //            city: user.community.cityId,
            //            'aroundCommunity.0': {$exists: true}
            //        }, {fromFlag: 'operate'}]
            //    }
        } else {
            if (category == 'question') {
                opt['$and'] = [{$or: [{community: currCommunityId}, {aroundCommunity: currCommunityId}, {fromFlag: 'operate'}]}, // 新：前端传递小区
                    // opt['$and'] = [{$or: [{community: user.community._id}, {aroundCommunity: user.community._id}, {fromFlag: 'operate'}]}, // 旧：原来是取得登陆用户所在小区
                    {
                        $or: [{category: 'question', isShow: null}, {category: 'lostAndFound', isShow: null}, {
                            isShow: -1,
                            createdBy: user._id
                        }]
                    }];
            } else if (category == 'share') {
                opt['$and'] = [{$or: [{community: currCommunityId}, {aroundCommunity: currCommunityId}, {fromFlag: 'operate'}]}, // 新：前端传递小区
                    // opt['$and'] = [{$or: [{community: user.community._id}, {aroundCommunity: user.community._id}, {fromFlag: 'operate'}]}, // 旧：原来是取得登陆用户所在小区
                    {
                        $or: [{category: 'share', isShow: null}, {category: 'advertisement', isShow: null}, {
                            isShow: -1,
                            createdBy: user._id
                        }]
                    }];
            //} else if (category == 'all') {
            //    opt.fromFlag = {$ne: 'service'};
            //    opt['$or'] = [{aroundCommunity: user.community._id}, {fromFlag: 'operate'}]
            } else if (category == 'all') {
                opt.fromFlag = {$ne: 'service'};
                opt['$or'] = [
                    // {city: user.community.cityId}, // 旧
                    {city: currCityId},
                    {fromFlag: 'operate'},
                    {community: '54af7732fa7073d0511fee2a'}
                ];
                opt.community = {$ne: currCommunityId}; // 新：前端传递小区
                // opt.community = {$ne: user.community._id}; // 旧：原来是取得登陆用户所在小区
                opt.aroundCommunity = {$ne: null};
                opt.acrossCity = {$ne: 1};
            }
        }
    } else {                    //本小区 或父母小区

        /*opt.community = range == 'parent' ? user.parentCommunity : currCommunityId; // 新：前端传递小区*/
        /*  宝宝树66小区二次改造     add  guo  20170825   start   */
        //opt['$or'] = [{community: currCommunityId}, {topFlg:'3'}];//最新
        /*  宝宝树66小区二次改造    add   guo  20170825   end   */

        /*  宝宝树66小区二次改造     mod  guo.xiaomin  20170902   start   */
        // 全国运营贴
        // opt.community = range == 'parent' ? user.parentCommunity : currCommunityId; // 新：前端传递小区
        /*  宝宝树66小区二次改造     mod  guo.xiaomin  20170902   end   */

        /*opt.community = range == 'parent' ? user.parentCommunity : currCommunityId; // 新：前端传递小区*/

        /*  宝宝树66小区二次改造     mod  guo.xiaomin  20170831   start   */
        /*  宝宝树66小区二次改造     add  guo  20170825   start   */
        // opt['$or'] = [{community: currCommunityId}, {topFlg:'3'}];//最新 // 移动位置
        /*  宝宝树66小区二次改造    add   guo  20170825   end   */

        // opt.community = range == 'parent' ? user.parentCommunity : user.community._id; // 旧：原来是取得登陆用户所在小区

        var subOpt = {}; // 本小区
        if (category == 'question') {
            subOpt['$or'] = [{category: 'question'}, {category: 'lostAndFound'}];
        } else if (category == 'share') {
            subOpt['$or'] = [{category: 'share'}, {category: 'advertisement'}];
        } else if (category == 'all') {
            subOpt['$or'] = [{category: 'question'}, {category: 'lostAndFound'},
            /*  宝宝树66小区二次改造    mod   guo.xiaomin  20170814   start   */
            //  {category: 'share'}, {category: 'advertisement'}]; // 旧
            {category: 'share'}, {category: 'advertisement'}, {category: 'welcome'}]; // 新(welcome代表新人报道)
            /*  宝宝树66小区二次改造    mod   guo.xiaomin  20170814   end   */
        }

        if (subOpt['$or'] !== undefined) {
            subOpt['$or'].forEach(function (item) {
                item.isShow = null;
            });
            subOpt['$or'].push({isShow: -1, createdBy: user._id})
        }
        subOpt.community = currCommunityId;
        console.log('subOpt:::');
        console.log(subOpt);

        opt['$or'] = [];
        opt['$or'].push({topFlg: 3}); // 运营贴
        opt['$or'].push(subOpt); // 本小区帖子
        /*  宝宝树66小区二次改造     mod  guo.xiaomin  20170831   end   */
    }

    if (opt['$or'] !== undefined) {
        opt['$or'].forEach(function (item) {
            item.isShow = null;
        });
        opt['$or'].push({isShow: -1, createdBy: user._id})
    }

    console.log(opt);

    Question.find(opt, 'praiseCount _id desc categoryOrder community replies score ' +
        'category status images replies dateCreated createdBy topicId fromFlag level')
        .populate('replies.repliedBy', '_id nickName images userType authenticationStatus')
        .populate('community', '_id communityName location')
        .populate('createdBy', '_id nickName images authenticationStatus roomUnit showUnit userRole exp')
        .sort({dateCreated: -1}).limit(listPageSize).exec(function (err, results) {
            if (err) {
                callback(err, null)
            } else {

                exports.questionsHandle(results, user, function (err, results) {
                    var data = {};

                    //下拉刷新返回数据
                    if (direction == 'top' && results.length > 0) {

                        if (ts != '0') {
                            var count = results.length < listPageSize ? results.length : results.length + Math.ceil(Math.random() * 5);
                            data.refreshMsg = '更新了' + count + '条帖子';
                        }

                        //返回最新时间戳
                        data.latestTs = results[0].dateCreated.getTime();
                    }

                    //新帖子数量超过一页返回下一页时间戳
                    if (results.length >= listPageSize) {
                        data.nextTs = results[results.length - 1].dateCreated.getTime();
                    }

                    data.list = results;

                    // 周边小区不置顶

                    if (direction == 'top' && range != 'around') {
                        //  宝宝树66小区二次改造   全国修正功能添加 mod  luolh  20170724   start
                        // topFlg      0：没有置顶（默认值），1：全国，2：本小区
                        // 全国置顶或小区置顶
                        var findTopOpt = {
                            '$or' : [{community: currCommunityId, topFlg: 2}, {topFlg: 1}], // 新：前端传递小区
                            // '$or' : [{community: user.community._id}, {topFlg: 2}], // 旧：原来是取得登陆用户所在小区
                            isValid: true,
                            // isTop : true,
                            topBeginDate: {$lte: new Date()},
                            topEndDate: {$gte: new Date()}
                        }
                        Question.find(findTopOpt,
                            'praiseCount _id desc categoryOrder community replies ' +
                            'category status images replies dateCreated createdBy topicId level topFlg')
                            .populate('replies.repliedBy', '_id nickName images userType authenticationStatus')
                            .populate('community', '_id communityName location')
                            .populate('createdBy', '_id nickName images authenticationStatus roomUnit showUnit userRole exp')
                            .sort({topFlg: 1})
                        // Question.find({
                        //     community: user.community._id,
                        //     isValid: true,
                        //     topBeginDate: {$lte: new Date()},
                        //     // category: category,
                        //     topEndDate: {$gte: new Date()}},
                        //     'praiseCount _id desc categoryOrder community replies ' +
                        //     'category status images replies dateCreated createdBy topicId level')
                        //     .populate('replies.repliedBy', '_id nickName images userType authenticationStatus')
                        //     .populate('community', '_id communityName location')
                        //     .populate('createdBy', '_id nickName images authenticationStatus roomUnit showUnit userRole exp'
                            // .limit(1)
                            //  宝宝树66小区二次改造   全国修正功能添加 mod  luolh  20170724   end
                            .exec(function (err, tops) {
                                exports.questionsHandle(tops, user, function (err, tops) {

                                    data.topList = tops;
                                    if (tops.length > 0)
                                        if(data && data.topList && data.topList[0]) {
                                            data.topList[0]._doc['isTop'] = true;
                                        }
                                    if (tops.length > 0) {
                                        var index;
                                        data.list.forEach(function (temp, i) {
                                            if (temp._id + '' == tops[0]._id + '') {
                                                index = i;
                                            }
                                        });
                                        if (index != null) {
                                            data.list.splice(index, 1)
                                        }
                                    }
                                    callback(err, data)
                                })
                            })
                    } else {
                        callback(err, data);
                    }
                });
            }
        });

};
/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170807   end   */

exports.questionsHandle = function (results, user, callback) {
    async.each(results, function (question, callback) {

        var distance = geolib.getDistance(
            {latitude: user.community.location.latitude, longitude: user.community.location.longitude},
            {latitude: question.community.location.latitude, longitude: question.community.location.longitude}
        );

        if (distance > 0 && question.fromFlag != 'operate')
            question._doc.distance = distance > 1000 ? (distance / 1000).toFixed(1) + 'km' : distance + 'm';

        if (question.topicId != null) {
            question._doc.topicUrl = h5Host + '/app/topic/index.html?tid=' + question.topicId;
        }

        //回复数、点赞数
        question._doc['replyCountStr'] = toolUtil.transformNumber(question.replies.length);
        question._doc.praiseCount = toolUtil.transformNumber(question.praiseCount);

        //采纳回复
        question.replies.forEach(function (reply) {
            if (reply.replyStatus == '已采纳') {
                question._doc['adoptedReply'] = reply;
            }
        });
        question.replies = undefined;

        question._doc['isTop'] = question.categoryOrder ? true : false;

        if (question.createdBy == null) {
            console.log('question.createdBy为空...question._id...' + question._id)
        }
        //等级
        if(question.createdBy) {
            question.createdBy._doc.level = toolUtil.getUserLevel(question.createdBy.exp ? question.createdBy.exp : 0);
        }

        //单元号
        var isOtherCommunity = user.community._id != question.community._id + '';
        if(question.createdBy) {
            if (question.createdBy.roomUnit != null && question.createdBy.roomUnit != '')
                question.createdBy._doc.roomUnit = !isNaN(question.createdBy.roomUnit) ? question.createdBy.roomUnit + '单元' : question.createdBy.roomUnit;
            if ((question.createdBy.showUnit != null && !question.createdBy.showUnit) || isOtherCommunity) {
                question.createdBy.roomUnit = undefined;
            }
        }

        /*  宝宝树66小区二次改造    mod   dayu  20170727   start   */
        //分享url
        //question._doc.shareUrl = 'http://' + backOfficeHost + QUESTION_SHARE_URL + '?v=1.0';
        question._doc.shareUrl = 'http://' + questionShareHost + QUESTION_SHARE_URL + '?v=1.0';
        /*  宝宝树66小区二次改造    mod   dayu  20170727   end   */

        async.parallel([
            function (callbackInner) {              //是否点赞
                questionPraise.findOne({
                    question: question._id, user: user._id
                }, function (err, result) {
                    question._doc.isPraise = result != null;
                    callbackInner();
                })
            },
            function (callbackInner) {              //采纳回复替换@
                if (question._doc.adoptedReply != null && question._doc.adoptedReply.replyDesc.indexOf(atFlag) != -1) {
                    replyAt.findOne({replyId: question._doc.adoptedReply._id + ''}, function (err, at) {
                        if (at != null && at.uList != null) {
                            at.uList.forEach(function (temp, i) {
                                question._doc.adoptedReply.replyDesc = question._doc.adoptedReply.replyDesc.replace(new RegExp("@\\{" + i + "\\}"), '@' + temp.nickName + ' ')
                            });
                        }
                        callbackInner();
                    }).populate('uList', '_id nickName');
                } else {
                    callbackInner();
                }
            }
        ], callback)
    }, function (err) {
        callback(err, results);
    });
};


/**
 * 获取回复列表
 * @param user
 * @param ts
 * @param id
 * @param callback
 */
exports.getReplyListService = function (user, ts, id, callback) {
    Question.findOne({
        _id: id,
        isValid: true
        //$or: [{isShow: null}, {createdBy: user._id, isShow: -1}]
    }, 'createdBy replies category')
        .populate('replies.repliedBy', '_id nickName images authenticationStatus showUnit roomUnit userRole exp')
        .populate('replies.replyTo', '_id nickName')
        .populate('replies.community', 'communityName location')
        .exec(function (err, result) {
            if (err) logger.error(err.message);
            if (result == null) {
                callback({message: '这个帖子已被删除'})
            } else {
                result.replies.sort(function (a, b) {
                    a.displayOrder = a.displayOrder ? a.displayOrder : 0;
                    b.displayOrder = b.displayOrder ? b.displayOrder : 0;

                    if (a.displayOrder > b.displayOrder) {
                        return -1
                    } else if (a.displayOrder < b.displayOrder) {
                        return 1
                    } else {
                        return b.dateReplied - a.dateReplied
                    }
                });

                var index = result.replies.length;

                if (ts != '0') {
                    for (i = 0; i < result.replies.length; i++) {
                        var reply = result.replies[i];
                        if (reply.replyStatus == '未采纳' && reply.dateReplied.getTime() < Number(ts)) {
                            index = i;
                            break;
                        }
                    }
                } else {
                    index = 0;
                }


                var data = result.replies.slice(index, index + listPageSize);

                async.each(data, function (reply, callbackInner) {


                    //回复者单元显示
                    if (reply.community != null) {
                        var isOtherCommunity = user.community._id != reply.community._id + '';

                        var distance = geolib.getDistance(
                            {latitude: user.community.location.latitude, longitude: user.community.location.longitude},
                            {latitude: reply.community.location.latitude, longitude: reply.community.location.longitude}
                        );

                        if (distance > 0)
                            reply._doc.distance = distance > 1000 ? (distance / 1000).toFixed(1) + 'km' : distance + 'm';
                    }
                    if (reply.repliedBy.roomUnit != null && reply.repliedBy.roomUnit != '')
                        reply.repliedBy._doc.roomUnit = !isNaN(reply.repliedBy.roomUnit) ? reply.repliedBy.roomUnit + '单元' : reply.repliedBy.roomUnit;
                    if ((reply.repliedBy.showUnit != null && !reply.repliedBy.showUnit) || isOtherCommunity) {
                        reply.repliedBy.roomUnit = undefined;
                    }
                    reply.repliedBy.showUnit = undefined;

                    //等级
                    reply.repliedBy._doc.level = toolUtil.getUserLevel(reply.repliedBy.exp ? reply.repliedBy.exp : 0);

                    //去多余字段
                    reply.displayOrder = undefined;


                    async.parallel([
                        function (cb) {
                            QuestionReplyThank.findOne({
                                reply: reply._id, user: result.createdBy
                            }, function (err, result) {
                                reply._doc.isThank = result != null;
                                cb();
                            });
                        },
                        function (cb) {
                            if (reply.replyDesc.indexOf(atFlag) != -1) {
                                replyAt.findOne({replyId: reply._id + ''}, function (err, at) {
                                    if (at != null && at.uList != null) {
                                        reply._doc['uList'] = at.uList;
                                    }
                                    cb();
                                }).populate('uList', '_id nickName');
                            } else {
                                cb()
                            }
                        },
                        function (cb) {
                            if (reply.replyTo != null && reply.quoteId != null) {
                                var quote;
                                result.replies.forEach(function (r) {
                                    if (reply.quoteId == r._id + '') {
                                        quote = reply.replyTo.nickName + '说：' + (r.replyDesc ? r.replyDesc : '');
                                    }
                                });
                                if (quote != null && quote.indexOf(atFlag) != -1) {
                                    replyAt.findOne({replyId: reply.quoteId}, function (err, at) {
                                        if (at != null && at.uList != null) {
                                            at.uList.forEach(function (temp, i) {
                                                quote = quote.replace(new RegExp("@\\{" + i + "\\}"), '@' + temp.nickName + ' ')
                                            });
                                        }
                                        reply._doc.quote = quote;
                                        cb();
                                    }).populate('uList', '_id nickName');
                                } else {
                                    if (quote)reply._doc.quote = quote;
                                    cb();
                                }
                            } else {
                                cb();
                            }
                        }
                    ], callbackInner)
                }, function (err) {
                    var res = {
                        ts: data.length > 0 ? data[data.length - 1].dateReplied.getTime() : new Date("2000/04/01").getTime(),
                        replies: data,
                        category: result.category == 'advertisement' ? 'share' : result.category,
                        replyCount: toolUtil.transformNumber(result.replies.length)
                    };
                    callback(err, res)
                })
            }
        })
};


exports.getMyAdoptReplyListService = function (user, ts, callback) {
    var date = ts == '0' ? new Date() : new Date(Number(ts));
    replyIndex.find({
        repliedBy: user._id,
        replyStatus: '已采纳',
        dateReplied: {$lt: date}
    }, 'contentId replyId -_id dateReplied')
        .sort({dateReplied: -1}).limit(listPageSize)
        .exec(function (err, results) {
            if (results != null) {
                async.each(results, function (index, callbackInner) {
                    Question.findOne({_id: index.contentId}, 'desc images createdBy category replies dateCreated')
                        .populate('createdBy', 'nickName images')
                        .exec(function (err, question) {
                            if (question != null) {
                                question.replies.forEach(function (reply) {
                                    if (reply._id + '' == index.replyId) {
                                        index._doc.reply = reply;
                                    }
                                });

                                question.replies = undefined;

                                index._doc.question = question;

                                if (index._doc.reply != null && index._doc.reply.replyDesc.indexOf(atFlag) != -1) {
                                    replyAt.findOne({replyId: index.replyId}, function (err, at) {
                                        if (at != null && at.uList != null) {
                                            at.uList.forEach(function (temp, i) {
                                                index._doc.reply.replyDesc = index._doc.reply.replyDesc.replace(new RegExp("@\\{" + i + "\\}"), '@' + temp.nickName + ' ')
                                            });
                                        }
                                        callbackInner()
                                    }).populate('uList', '_id nickName');
                                } else {
                                    callbackInner()
                                }

                            } else {
                                callbackInner();
                            }
                        })
                }, function (err) {
                    callback(err, results);
                })
            } else {
                callback(err, []);
            }
        })
};

exports.getMyReplyListService = function (user, ts, callback) {
    var date = ts == '0' ? new Date() : new Date(Number(ts));
    replyIndex.find({
        repliedBy: user._id,
        dateReplied: {$lt: date}
    }, 'contentId replyId -_id dateReplied')
        .sort({dateReplied: -1}).limit(listPageSize)
        .exec(function (err, results) {
            if (results != null) {
                async.each(results, function (index, callbackInner) {
                    Question.findOne({_id: index.contentId}, 'desc images createdBy category replies dateCreated topicId')
                        .populate('createdBy', 'nickName images')
                        .exec(function (err, question) {
                            if (question != null) {
                                question.replies.forEach(function (reply) {
                                    if (reply._id + '' == index.replyId) {
                                        index._doc.reply = reply;
                                    }
                                });

                                if (question.topicId != null)
                                    question._doc.topicUrl = h5Host + '/app/topic/index.html?tid=' + question.topicId;
                                question.replies = undefined;
                                index._doc.question = question;


                                if (index._doc.reply != null && index._doc.reply.replyDesc.indexOf(atFlag) != -1) {
                                    replyAt.findOne({replyId: index.replyId}, function (err, at) {
                                        if (at != null && at.uList != null) {
                                            at.uList.forEach(function (temp, i) {
                                                index._doc.reply.replyDesc = index._doc.reply.replyDesc.replace(new RegExp("@\\{" + i + "\\}"), '@' + temp.nickName + ' ')
                                            });
                                        }
                                        callbackInner()
                                    }).populate('uList', '_id nickName');
                                } else {
                                    callbackInner()
                                }
                            } else {
                                callbackInner();
                            }
                        })
                }, function (err) {
                    callback(err, results);
                })
            } else {
                callback(err, []);
            }
        })
};

/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170807   start   */
// 前端选择其他小区
exports.getOwnMutualAidListService = function (user, ts, direction, currCommunityId, currCityId, callback) { // 新:前台传递小区
    // exports.getOwnMutualAidListService = function (user, ts, direction, callback) { // 旧:无前台传递小区
    async.parallel([
        function (callbackInner) {
            exports.getListService(user, ts, direction, 'own', 'all', null, 300, currCommunityId, currCityId, callbackInner);
        },
        function (callbackInner) {
            if (direction == 'top') {
                exports.getBannerListService(user, 1, callbackInner);
            } else {
                callbackInner();
            }
        }
    ], function (err, result) {
        if (result[1] != null) result[0].bannerList = result[1];
        callback(err, result[0]);
    });
};
/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170807   end   */

/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170807   start   */
// 前端选择其他小区
exports.getAroundMutualAidListService = function (user, ts, direction, currCommunityId, currCityId, callback) { // 新:前台传递小区
    // exports.getAroundMutualAidListService = function (user, ts, direction, callback) { // 旧:无前台传递小区

    redisClient.HGET('community:user:count', currCommunityId, function (err, value) { // 新：前端传递小区
        // redisClient.HGET('community:user:count', user.community._id, function (err, value) { // 旧：原来是取得登陆用户所在小区

        async.parallel([
            function (callbackInner) {
                exports.getListService(user, ts, direction, 'around', 'all', null, Number(value), currCommunityId, currCityId, callbackInner);
            },
            function (callbackInner) {
                if (direction == 'top') {
                    exports.getBannerListService(user, 3, callbackInner);
                } else {
                    callbackInner();
                }
            }
        ], function (err, result) {
            if (result[1] != null) result[0].bannerList = result[1];
            callback(err, result[0]);
        });

    });
};
/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170807   end   */

/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170807   start   */
// 前端选择其他小区-共同方法加参数了
exports.getParentMutualAidListService = function (user, ts, direction, callback) {
    exports.getListService(user, ts, direction, 'parent', 'all', null, null, null, null, callback)
};
/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170807   end   */

exports.getMutualAidTablesService = function (user, callback) {
    var data = {
        tables: [
            {
                name: '本小区',
                category: 'own'
            },
            {
                name: '周边小区',
                category: 'around'
            }
        ]
    };

    callback(null, data);
};

/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170807   start   */
// 前端选择其他小区
// exports.getMutualAidPageDataService = function (user, ts, category, direction, parentCommunity, callback) { // 旧:无前台传递小区
exports.getMutualAidPageDataService = function (user, ts, category, direction, parentCommunity, currCommunityId, currCityId, callback) { // 新:前台传递小区

    switch (category) {
        case 'question': // 问问?
            // exports.getQuestionListService(user, ts, 'around', direction, null,, callback); // 旧:无前台传递小区
            exports.getQuestionListService(user, ts, 'around', direction, null, currCommunityId, currCityId, callback); // 新:前台传递小区
            break;
        case 'share': // 分享?
            // exports.getShareListService(user, ts, 'around', direction, callback); // 旧:无前台传递小区
            exports.getShareListService(user, ts, 'around', direction, currCommunityId, currCityId, callback); // 新:前台传递小区
            break;
        case 'own': // 自己所在?
            // exports.getOwnMutualAidListService(user, ts, direction, callback); // 旧:无前台传递小区
            exports.getOwnMutualAidListService(user, ts, direction, currCommunityId, currCityId, callback); // 新:前台传递小区
            break;
        case 'around': // 周边?
            // exports.getAroundMutualAidListService(user, ts, direction, callback); // 旧:无前台传递小区
            exports.getAroundMutualAidListService(user, ts, direction, currCommunityId, currCityId, callback); // 新:前台传递小区
            break;
        case 'parent':
            user.parentCommunity = parentCommunity;
            exports.getParentMutualAidListService(user, ts, direction, callback);
            break;
        default :
            callback(null, {nextTs: 0, list: []});
            break;
    }
};
/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170807   end   */

exports.getBannerListService = function (user, type, callback) {
    Banner.find({
        beginDate: {$lte: new Date()},
        endDate: {$gte: new Date()},
        type: type,
        isValid: true,
        $or: [
            {city: user.community.cityId},
            {level: 0}]
    }, '_id url imageURL name openType contentId beginDate endDate').exec(function (err, temp) {
        var bannerList = [];
        if (temp == null) return callback(null, bannerList);
        temp.forEach(function (banner) {
            var temp = {
                category: 'banner',
                url: banner.url,
                images: [{
                    imageURL: imgHost + banner.imageURL + '?imageView2/1/h/276/w/750/q/75'
                }],
                bannerIndex: bannerIndex,
                beginDate: banner.beginDate,
                endDate: banner.endDate
            };
            if (banner.openType) temp.openType = banner.openType;
            if (banner.contentId) temp.contentId = banner.contentId;

            bannerList.push(temp);
        });
        return callback(null, bannerList);
    });
};

exports.createWelcomeQuestionService = function (user) {
    //Users.findOne({"mobilePhone": "66customerservice"}, '_id', function (err, service) {
    var temp = new Question();
    // 新版本改发到求助
    // temp.category = 'question';
    temp.category = 'welcome';
    temp.desc = '新人报到，大家多支持。';
    temp.createdBy = user._id;
    temp.community = user.community._id;
    temp.city = user.community.cityId;
    temp.fromFlag = 'welcome';
    temp.save();
    //})
};
